import { Connection } from 'mongoose';
import { getInstance } from '../../db';
import { userRelationSchema } from '../../schemas/userRelationSchema';

const getFriendList = async (uid: string) => {
  if (!uid) {
    return;
  }
  const db: Connection = await getInstance();

  // 应该把这些获取model的方法统一封装到shcma里面，这样不用重复的写获取函数
  const userRelationModel = db.model('userRelationModel', userRelationSchema);

  const result = await userRelationModel.aggregate([
    {
      $match: {
        userId: uid,
      },
    },
    {
      $lookup: {
        from: 'account',
        localField: 'fromUser',
        foreignField: 'uid',
        as: 'account',
      },
    },
    // 扁平数组
    {
      $unwind: {
        path: '$account',
        preserveNullAndEmptyArrays: true,
      }
    },
    // 只需要特定的数据
    {
      $project: {
        _id: 1,
        userId: 1,
        fromUser: 1,
        time: 1,
        status: 1,
        profile: "$account.profile",
        username: "$account.username",
      }
    }
  ])

  // console.log(uid, result, '????');

  return result;
}

export const isFriend = async (params: IAnyObject) => {
  const { userId, fromUser } = params;

  const db: Connection = await getInstance();

  // 应该把这些获取model的方法统一封装到shcma里面，这样不用重复的写获取函数
  const userRelationModel = db.model('userRelationModel', userRelationSchema);

  const result = await userRelationModel.find({ 
    userId: {
      $eq: userId,
    },
    fromUser: {
      $eq: fromUser,
    }
  })

  return result;
}

export default getFriendList;